// app.js
App({
  onLaunch() {
    // 展示本地存储能力
    const logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

  },
  globalData: {
    prefixUrl:'http://localhost:8080',//'http://localhost:8080'
    userInfo: null,
    openId:'',
    userId:0,
    token:'',
    agent:false,
  },
  login(e){
    var that=this
    return new Promise(function(resolve, reject) {
      wx.login({
        success: res => {
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
          var code=res.code;
          if(code){
            wx.request({
              url: that.globalData.prefixUrl+'/user/wechat/'+code,
              success(e){
                that.globalData.openId=e.data.data.openId
                console.log(that.globalData.openId)
                wx.request({
                  url: that.globalData.prefixUrl+"/user/"+that.globalData.openId,
                  success(e){
                    console.log(e)
                    that.globalData.userInfo=e.data.data
                    that.globalData.token=e.header.Authorization
                    that.globalData.userId=e.data.data.id
                    console.log('测试',that.globalData.token)
                    if(e.data.code==601){
                      wx.showModal({
                        title: '提示',
                        content: '您还未注册，无法使用所有功，点击确定前往注册',
                        success (res) {
                          if (res.confirm) {
                            console.log('用户点击确定')
                            wx.navigateTo({
                              url: '/pages/register/register',
                            })
                          } else if (res.cancel) {
                            console.log('用户点击取消')
                          }
                        }
                      })
                    }
                    if(that.globalData.userInfo.isValid==false){
                      for(var i=0;;i++){
                        wx.showModal({
                          title: '提示',
                          content: '您不能使用此小程序，请联系管理员',
                          success (res) {
                          }
                        })
                      }
                    }
                    resolve()
                  }
                })
              },fail(e){
                wx.showToast({
                  icon: 'error',
                  title: '网络连接失败',
                })
              }
            })
          }
        }
      })
    })
  }
})
